import setting from '@/utils/setting'
import { showToast } from '@nutui/nutui'

type options = {
  data?: Record<string, any>
  headers?: Record<string, any>
  isJson?: boolean
}

const request = async (url: string, method: 'POST' | 'GET' = 'GET', options?: options) => {
  const { headers = {}, data, isJson = true } = options || {}

  if (method === 'GET' && data) {
    const schema = new URLSearchParams(data)
    url += '?' + schema.toString()
  }

  const isFormData = data instanceof FormData
  const body = isFormData ? data : data && method !== 'GET' ? JSON.stringify(data) : undefined

  if (!isFormData) {
    headers['Content-Type'] = 'application/json'
  }

  const response = await fetch(setting.host + url, {
    method,
    body,
    headers,
  })

  if (isJson) {
    const result = await response.json()
    if (result.code !== 0) {
      showToast.text(result.msg || '请求失败')
      return Promise.reject(result)
    }

    return result.data
  } else {
    const result = await response.text()
    return result
  }
}

export default request
